##################################################################
# File : /lua/ui/network/gameclient.lua
# Description : Dark Skies networking module
# Author : Neruz
##################################################################

local internalComm = import('/lua/ui/network/lobbycomm.lua')
local UIUtil = import('/lua/ui/uiutil.lua')

GameClient = Class(internalComm.LobbyComm) {

	ConnectionFailed = function(self, reason)
		self.connectdialog.textLine[1]:SetText("Connection failed: " .. reason)
	end,
	
    ConnectionToHostEstablished = function(self, localId, localName,hostId)
    	_G.DSSocket = self
    	self.players = {}
    	local armyData = GetArmiesTable().armiesTable[1]
    	self:SendData(0, {_type = "PlayerJoined", playerData = {requestedName = localName, armyData = armyData}})
		KillThread(self.timeoutThread)
		self.connectdialog.textLine[1]:SetText("Connection established.")
		self.connectdialog:Destroy()
    end,
    
	DataReceived = function(self, data)
		local _type = data._type
		local senderId = data.SenderID
		local senderName = data.SenderName
		if _type == "PlayerInfo" then
			local players = data.players
			for k, playerData in players do
				self.players[playerData.playerId] = playerData
-- 		    	for i, func in self._callbacks['PlayerJoined'] do
-- 		    		func(playerData.playerId)
-- 		    	end
			end
		elseif _type == "PlayerSync" then
			self.players[data.playerId] = data.playerData
-- 	    	for i, func in self._callbacks['PlayerJoined'] do
-- 	    		func(data.playerId)
-- 	    	end
		elseif _type == "ChatMessage" then
			local chatData = data.ChatData
			import('/lua/ui/game/chat.lua').ReceiveChat(senderName, chatData)
		end
	end,
	
	SendData = function(self, targetId, data)
		internalComm.LobbyComm.SendData(self, targetId, data)
	end,
	
	BroadcastData = function(self, data)
		internalComm.LobbyComm.BroadcastData(self, data)
	end,
	
	SystemMessage = function(self, text)
	end,
	
	JoinGame = function(self, addr, remotePlayerName, remotePlayerUID)
		self.connectdialog = UIUtil.ShowInfoDialog(HUDParent, "Connecting to Game Server...", "Abort", function() ExitGame() end)
		self.timeoutThread = ForkThread(function()
			WaitSeconds(DSinternalComm.quietTimeout / 1000)
			self:ConnectionFailed(LOC(DSinternalComm.Strings.TimedOutToHost))
		end)
		internalComm.LobbyComm.JoinGame(self, addr, remotePlayerName, remotePlayerUID)
	end,
	
    PeerDisconnected = function(self, peerName, peerId)
    	WARN('PeerDisconnected', peerName, peerId)
    	self.players[peerId] = nil
--     	for i, func in self._callbacks['PlayerLeft'] do
--     		func(peerId)
--     	end
    end,
    
    PeerConnected = function(self, peerName, peerId)
    	WARN('PeerConnected')
    end,
}

function InitGameClient(protocol)
    local comm = GameClient(protocol, 0, internalComm.maxConnections, "gameClient", nil, nil)
    return comm
end